package top.jfunc.websocket.config;

import redis.clients.jedis.Jedis;
import top.jfunc.websocket.TodoAtRemoved;
import top.jfunc.websocket.WebSocketManagerUtil;
import top.jfunc.websocket.memory.MemWebSocketManager;
import top.jfunc.websocket.redis.RedisWebSocketManager;
import top.jfunc.websocket.redis.Subscriber;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author xiongshiyan at 2019/4/20 , contact me with email yanshixiong@126.com or phone 15208384257
 */
public class WebSocketManagerConfig {
    /**
     * 基于内存的单机 WebSocketManager
     */
    public static void configMemory(){
        WebSocketManagerUtil.setWebSocketManager(new MemWebSocketManager());
    }
    /**
     * 基于Redis的集群 WebSocketManager
     */
    public static void configCluster(Jedis jedis){
        jedis.subscribe(new Subscriber() , RedisWebSocketManager.CHANNEL);
        WebSocketManagerUtil.setWebSocketManager(new RedisWebSocketManager(jedis));
    }

    /**
     * 配置心跳监测
     * @param period 多长时间执行一次
     * @param timeSpan 时间间隔
     * @param errorTolerant 错误容忍次数
     * @param todoAtRemoved 干什么
     */
    public static void configHeartBeatCheck(int period , long timeSpan , int errorTolerant , TodoAtRemoved todoAtRemoved){
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(()->{
            WebSocketHeartBeatChecker.INSTANCE.check(
                    WebSocketManagerUtil.getWebSocketManager() ,
                    timeSpan , errorTolerant, todoAtRemoved);
        } , 0 , period , TimeUnit.SECONDS);
    }
}
